package com.lovi.thread_;

import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 管理线程
 */
@Data
public class ManageServerConnectClientThread{
    //把连接线程加入到集合里<hashmap>方便找到线程
    //多线程情况下，用ConcurrentHashMap线程安全
    private static ConcurrentHashMap <String,ServerConnectClientThread> serverConnectClientThreadsMap = new ConcurrentHashMap<>();

    /**
     * 添加方法
     */
    public static void  addServerConnectClientThread(String userId,ServerConnectClientThread serverConnectClientThread){
        serverConnectClientThreadsMap.put(userId,serverConnectClientThread);
    }
    /**
     * 查找方法
     */
    public static ServerConnectClientThread getServerConnectClientThread(String userId){
        return serverConnectClientThreadsMap.get(userId);
    }
    /**
     * 获取在线用户列表
     */
    public static String getOnlineUsers(){
        String result = "";
        ConcurrentHashMap.KeySetView<String, ServerConnectClientThread> strings
                = serverConnectClientThreadsMap.keySet();
        for (String key : strings) {
            result += key + " ";
        }

        return result;
    }

    /**
     * 获取在线用户列表
     * @return
     */
    public static List<String> getOnlineUsers2(){
        ArrayList<String> list = new ArrayList<>();
        ConcurrentHashMap.KeySetView<String, ServerConnectClientThread> strings
                = serverConnectClientThreadsMap.keySet();
        list.addAll(strings);
        return list;
    }

    public static void removeServerConnectClientThread(String userId) {
        serverConnectClientThreadsMap.remove(userId);
    }
}
